package com.fesine.learn.design.pattern.creational.singleton;

/**
 * @description: 懒汉单例模式
 * @author: fesine
 * @createTime:2019/2/20
 * @update:修改内容
 * @author: fesine
 * @updateTime:2019/2/20
 */
public class LazyDoubleCheckSingleton {
    /**
     * 私有静态变量
     * volatile保证内存可见性，防止出现因重排序导致对象创建错误
     */
    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton = null;

    /**
     * 私有构造器
     */
    private LazyDoubleCheckSingleton(){}

    public  static LazyDoubleCheckSingleton getInstance(){
        if(lazyDoubleCheckSingleton == null){
            synchronized (LazyDoubleCheckSingleton.class){
                if(lazyDoubleCheckSingleton == null){
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton();
                    //new LazyDoubleCheckSingleton() 共经历三个步骤
                    //1.分配内存给这个对象
                    //3.设置lazyDoubleCheckSingleton指向刚分配的内存地址 --2和3重排序，单线程中没有问题
                    //2.初始化对象
                    //-----------3.设置lazyDoubleCheckSingleton指向刚分配的内存地址
                }
            }
        }
        return lazyDoubleCheckSingleton;
    }
}
